﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;


/// <summary>
/// 网络调用工具
/// </summary>
public class HttpUtility
{
	public HttpUtility()
	{		
	}

    public static void AsyncHttpRequest(string address,ReadDataComplectedEventHandler callback)
    {       
        new AsyncWebRequest(address).BeginReuest(callback);
    }

    public static string HttpRequest(string address)
    {
        return HttpRequest(address, null, Encoding.UTF8,null);
    }

    public static string HttpRequest(string address,string postData, Encoding encode,CookieContainer cookies)
    {
        if (encode == null)
        {
            encode = Encoding.GetEncoding("GB2312");
        }
        CookieContainer cookie = null;
        if (cookies != null)
        {
            cookie = cookies;
        }
        string html = String.Empty;
        bool m_UsePost = false;
        if (postData == null || postData.Length == 0)
        {
            m_UsePost = false;
        }
        else
        {
            m_UsePost = true;
        }
        try
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(address);
            req.Method = m_UsePost ? "POST" : "GET";
            Uri u = new Uri(address);
            req.Referer = address.Split(':')[0] + "://" + u.DnsSafeHost;
            req.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2243.0 Safari/537.36";
            req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            req.KeepAlive = true;
            req.Accept = "*/*";
            
            if (cookie != null)
            {
                req.CookieContainer = cookie;
            }
            if (m_UsePost)
            {
                req.ContentLength = postData.Length;
                using (StreamWriter writer = new StreamWriter(req.GetRequestStream()))
                {
                    byte[] bytes = Encoding.ASCII.GetBytes(postData);
                    writer.Write(bytes);
                    writer.Close();
                }
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            if (cookie != null)
            {
                resp.Cookies = cookie.GetCookies(new Uri(address));
            }
            StreamReader sr = new StreamReader(resp.GetResponseStream(), encode);
            html = sr.ReadToEnd();
            sr.Close();
            resp.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return html;
    }

}